package org.hoyi.dispatchfact;

import java.lang.reflect.Constructor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hoyi.DB.conf.HOYIConf;
import org.hoyi.DB.ctrl.Console;
import org.hoyi.dishop.Hoyipage;
import org.hoyi.dispatchs.responseUtil;
import org.hoyi.disptachs.model.JsonModel;
import org.hoyi.microservice.HoyiCloudApplication;
import org.hoyi.wb.comment.RequestType;

public class HoyiPageDispatcher implements IDispatcher{

	@Override
	public boolean doSth(HttpServletRequest _request, HttpServletResponse _response, String _requrl, RequestType _reqType) {
		if (_requrl.toLowerCase().endsWith(HOYIConf.Suffix)) {
			_requrl = _requrl.replace(HOYIConf.Suffix, ".class");

			if (_requrl.startsWith("/")) {
				_requrl = _requrl.substring(1);
			}
			if (_requrl.contains("/")) {
				_requrl = _requrl.replace("/", ".");
			}
			if (_requrl.contains("\\")) {
				_requrl = _requrl.replace("\\", ".");
			}
			_requrl = _requrl.replace(".class", "");
		}else{
			return false;
		}

		Console.Info("_requrl:" + _requrl);
		Class disp = null;
		String reqclass = "WebRoot." + _requrl;
		try {
			disp = Thread.currentThread().getContextClassLoader().loadClass(reqclass);
			
			Constructor[] cons = disp.getConstructors();
			Hoyipage page = (Hoyipage) cons[0].newInstance(new Object[0]);

			// 这里读取到后，判断page能访问的类型是否包含在当前访问类型内.
			page.currentReqType = _reqType;
			page.InitAndLoadRequestType();
			// 如果验证能通过.
			if (page.ValidateReq()) {
				_request.setCharacterEncoding("UTF-8");
				page.setRequest(_request);
				page.setResponse(_response);
				page.OnPreInit();

				if (!page.Behaviored)
					;
			} else {
				JsonModel model = new JsonModel(-998, "Request Type is not allow.requesturl:" + _requrl);
				responseUtil.getinstance().WriteUTF8JSON(_response, model);
			}
			return true;
		} catch (Exception e) {
			Console.Error(e);
			return false;
		}
	}
}
